package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    @Transactional
    public OrderSubmitVO saveSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //在orders表插入数据
        Orders orders = new Orders();
        //userId
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);
        AddressBook address = addressBookMapper.findById(ordersSubmitDTO.getAddressBookId());
        orders.setConsignee(address.getConsignee());
        orders.setAddress(address.getDetail());
        orders.setPhone(address.getPhone());
        orders.setUserName(user.getName());
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        ordersMapper.insert(orders);

        //向order_detail插数据
        Long ordersId = orders.getId();
        List<ShoppingCart> shopCarlist = shoppingCartMapper.list(userId);
        for (ShoppingCart shoppingCart : shopCarlist) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(ordersId);
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetailMapper.insert(orderDetail);
        }

        shoppingCartMapper.del(userId);

        //返回值
        OrderSubmitVO order = OrderSubmitVO.builder()
                .id(ordersId)
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return order;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.findById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordersMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //通过websocket通知客户端订单支付成功
        Map map = new HashMap();
        map.put("type", 1); //1.来了订单提醒  2.催单提醒
        map.put("orderId", ordersDB.getId());
        map.put("content","来新订单了："+outTradeNo);

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = ordersMapper.findById(id);
        //通过websocket通知客户端订单支付成功
        Map map = new HashMap();
        map.put("type", 2); //1.来了订单提醒  2.催单提醒
        map.put("orderId",id);
        map.put("content","用户催单了："+orders.getNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);

    }
}
